<!DOCTYPE html>
<html>
<head>
    <!--Import Google Icon Font-->
    <link type="text/css" rel="stylesheet" href="css/material-icons.css"/>
    <!--Import materialize.css-->
    <link type="text/css" rel="stylesheet" href="css/materialize.min.css" media="screen,projection"/>
    <title>Build Disk Image</title>

    <!--Let browser know website is optimized for mobile-->
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>

</head>
<body>
<div class="container">
    <div class="section">
        <div class="row">
            <div class="col m6 push-m2" id="main-panel">
              <div class="row">
                  <div class="input-field col m4">
                      <input id="image_name" placeholder="input image name" type="text" class="validate" name="name" required>
                      <label for="image_name" id="name-label"></label>
                  </div>
              </div>
              <div class="row">
                  <div class="input-field col m8">
                      <textarea id="description" placeholder="descript this image" class="materialize-textarea" required></textarea>
                      <label for="description" id="description-label"></label>
                  </div>
              </div>
              <div class="row">
                <div class="col m2">
                  <label id="tag-label"></label>
                </div>
              </div>
              <div class="row">
                  <div class="col m8">
                    <div class="row" id="tag-list">
                    </div>
                  </div>
              </div>
              <div class="row">
                <div class="input-field col m3">
                  <select id="pool-options" onchange="onFilterPoolChanged()">
                  </select>
                  <label id="pool-label"></label>
                </div>
              </div>
              <div class="row">
                <div class="input-field col m8">
                  <select id="guest-options">
                  </select>
                  <label id="instance-label"></label>
                </div>
              </div>
            </div>
        </div>
    </div>
    <div class="divider"></div>
    <div class="section">
        <div class="row">
            <div class="col m2">
                <a class="waves-effect waves-light blue-grey lighten-2 btn" onclick="window.history.back()" id="back-caption"><i
                        class="material-icons left">chevron_left</i></a>
            </div>
            <div class="col m2 right" id="button">
                <button class="waves-effect waves-light blue-grey lighten-2 btn" onclick="buildImage()" id="build-caption">
                    <i class="material-icons right">build</i>
                </button>
            </div>
        </div>
    </div>
</div>

<!--JavaScript at end of body for optimized loading-->
<script type="text/javascript" src="js/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="js/materialize.min.js"></script>
<script type="text/javascript" src="js/nano.js"></script>
<script>

var texts = N.GetTexts();

$(function(){
  N.ValidateSession();
  $('#back-caption').append(texts.get(N.TagBack));
  $('#build-caption').prepend(texts.get(N.TagBuild));

  $('#name-label').text(texts.get(N.TagImageName));
  $('#description-label').text(texts.get(N.TagDescription));
  $('#tag-label').text(texts.get(N.TagTag));
  $('#pool-label').text(texts.get(N.TagComputePool));
  $('#instance-label').text(texts.get(N.TagInstance));

  //add tags
  var tagList = $('#tag-list');
  N.GetAllImageTags().forEach((tag)=>{
    tagList.append(
      $('<div>').addClass('col m3').append(
        $('<label>').append(
          $('<input>').attr('type', 'checkbox').attr('name', 'tag').val(tag[0])
        ).append(
          $('<span>').text(tag[1])
        )
      )
    );
  });

  M.AutoInit();
});

function buildImage(){
  var imageName = $('#image_name').val();
  if (!imageName){
    M.toast({html: 'invalid image name'});
    return;
  }
  var imageDescription = $('#description').val();
  if (!imageDescription){
    M.toast({html: 'input image description'});
    return;
  }

  var tags = new Array();
  $("input[name='tag']:checkbox:checked").each(function(){
    tags.push($(this).val());
  });

  var guest = $('#guest-options').val();
  if (!guest || ("" == guest)){
    M.toast({html: 'chosse source guest'});
    return;
  }
  createImage(imageName, imageDescription, tags, guest);
}

function releaseImage(id){
  $.ajax({
      url:'/disk_images/' + id,
      type: "DELETE",
      success: function (result) {
          if (0 != result['error_code']) {
              M.toast({html: 'release image fail: ' + result['message'], outDuration: 600});
              return;
          }
          M.toast({html: 'disk image "' + id + '" released'})
          setTimeout(refresh, 1500);
      }
  });
}

function createImage(name, description, tags, guest){
  var request = new Object();
  request.name = name;
  request.description = description;
  request.guest = guest;
  request.owner = N.GetCurrentUser();
  request.group = N.GetCurrentGroup();
  request.tags = tags;
  $.post(
    '/disk_images/',
    JSON.stringify(request),
    function(result){
      if (0 != result['error_code']) {
          M.toast({html: 'create disk image fail: ' + result['message'], outDuration: 600});
          return;
      }
      var imageId = result['data']['id'];
      startTransport(name, description, tags, guest, imageId);
    },
    "json"
  )
}

function startTransport(name, description, tags, guest, imageId){
  $('#button').empty();
  $('#main-panel').empty();
  var table = $('<table>').addClass('striped');
  table.append(
    $('<tr>').append(
      $('<td>').text(texts.get(N.TagName))
    ).append(
      $('<td>').text(name)
    )
  ).append(
    $('<tr>').append(
      $('<td>').text(texts.get(N.TagInstance))
    ).append(
      $('<td>').text(guest)
    )
  ).append(
    $('<tr>').append(
      $('<td>').text(texts.get(N.TagDescription))
    ).append(
      $('<td>').text(description)
    )
  ).append(
    $('<tr>').append(
      $('<td>').text(texts.get(N.TagTag))
    ).append(
      $('<td>').text(tags.join('/'))
    )
  ).append(
    $('<tr>').append(
      $('<td>').text('ID')
    ).append(
      $('<td>').text(imageId).attr('id', 'image_id')
    )
  ).append(
    $('<tr>').append(
      $('<td>').text(texts.get(N.TagResult))
    ).append(
      $('<td>').attr('id', 'operate_result').append(
        $('<div>').addClass('center').append(
          $('<span>').text('Building... 0%').attr('id', 'progress-info')
        )
      ).append(
        $('<div>').addClass('progress').append(
          $('<div>').addClass('determinate').width('0%').attr('id', 'progress-bar')
        )
      )
    )
  );
  $('#main-panel').append(table);
  monitorProgress();
}

function monitorProgress(){
  var imageID = $('#image_id').text();
  $.getJSON(
    '/disk_images/' + imageID,
    function(result){
      if (0 != result['error_code']) {
          M.toast({html: 'monitor progress fail:' + result['message']});
          releaseImage(imageID);
          return;
      }
      var created = result['data']['created'];
      if (created){
        $('#operate_result').text('success');
        $('#button').append(
          $('<a>').attr('href', '/images.html').append(
            $('<button>').addClass('waves-effect waves-light blue-grey lighten-2 btn').text(texts.get(N.TagFinish)).prepend(
              $('<i>').addClass('material-icons').text('check')
            )
          )
        );
        N.WriteOperateLog('build disk image ' + imageID);
        return;
      }
      var progress = result['data']['progress'] + '%';
      $('#progress-bar').width(progress);
      $('#progress-info').text('Creating... ' + progress);
      setTimeout(monitorProgress, 1000);
    }
  )
}

function onFilterPoolChanged(){
  var poolName = $('#pool-options').val();
  if ("" == poolName){
    return;
  }
  loadInstances(poolName);
}

function loadPools(){
  $.getJSON(
    '/compute_pools/',
    function(result){
      if (0 != result['error_code']) {
          M.toast({html: 'load pools fail:' + result['message']});
          return;
      }
      $('#pool-options').empty();
      result['data'].forEach((pool) =>{
        $('#pool-options').append(
          $('<option>').attr('value', pool['name']).text(pool['name'])
        );
      });
      M.FormSelect.init($('#pool-options'));
      onFilterPoolChanged();
    }
  );
}

function loadInstances(poolName){
  var queryURL = "/guest_search/?pool=" + poolName + '&session=' + N.GetSessionID();
  $.getJSON(
    queryURL,
    function(result){
      if (0 != result['error_code']) {
          M.toast({html: 'load instances fail:' + result['message']});
          return;
      }
      $('#guest-options').empty().append(
        $('<option>').attr('value','').attr('disabled','').attr('selected', '').text('Choose Guest')
      );
      result['data'].forEach((guest) =>{
        $('#guest-options').append(
          $('<option>').attr('value', guest['id']).text(guest['name'])
        );
      });
      M.FormSelect.init($('#guest-options'));
    }
  );
}

$(function(){
  loadPools();
});


</script>
</body>
</html>
